import { createApp } from 'vue'


import NProgress  from 'nprogress/nprogress'
import { router } from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import './assets/font/iconfont.css'
import { pinia } from '@/store/index'


import App from './App.vue'
const app = createApp(App).use(pinia)

import { getToken, removeToken } from '@/utils/auth'
import { userApi } from '@/api/user'
import { useUserStore } from '@/store/user'


const store = useUserStore(pinia)
router.beforeEach((to, from) => {
    if (to.path === '/')
        return {path:'/home'}
    NProgress.start()
 
    const { tokenValue, tokenName } = getToken()
    // 如果 存在tokenValue，则默认当前处于已登录状态
    // 若url: /login,则跳转到/index
    // 若url: 若是/login?query，则重新路由
    if (tokenValue && tokenName) {
        // 还存在tokenValue 和tokenName的值 
        // 再登录时，直接 跳转到/home
        // console.log('token: to.path:',to.path)
        if (to.path === '/login' || to.path==='/login/') {
            // 再登录时，直接 跳转到/home
            console.log('token, /login:', to)
            NProgress.done()
            return { name: 'home' }
        }
        else if (to.path.startsWith('/login')) {
            console.log('token, start login:', to)
            NProgress.done()
            return { path: to.path.substring(6)}
            // 带跳转路径 类似于/login?redirect:/user/get 
        } else {
            // console.log('具有token状态时访问url:', to.path)
                // 更新userstore信息,继续访问
                userApi.getLoginInfo().then(res => {
                    store.setUserInfo(res.data)
                }).catch(err => {
                    // 
                    /**
                    * 更新当前用户信息失败
                    * 可能原因网络的问题
                    * token 不正确,应该在repson截取到就处理
                    */
                    console.log('更新当前用户信息失败', err)


                    // userApi.logout().then(() => {
                    //     console.log(err)
                    //     return { path: '/' }
                    // })
                    // removeToken()
                })

            return true
        }
    } else {
        console.log('notoken, to.path: ',to.path)

        if (['/login','/login/', '/register'].indexOf(to.path) != -1) {
            // only 没有跳转
            console.log('notoken, only /login /register')
            return true
        }
        else if (to.path.startsWith('/login/')) {
            console.log('/notoken, login/register:', to.fullPath)

            return true
        } else {
            console.log('/notoken, others url:', to)
            NProgress.done()
            // return {name:'login'}
            // 对于 /login?xxxxx
            return { path: '/login' + to.fullPath }
        }
    }
}
)

router.afterEach((v) => {
    NProgress.done()
    // console.log(v)
})

import zhCn from 'element-plus/es/locale/lang/zh-cn'


app.use(ElementPlus, {
    locale: zhCn,
 }).use(router).mount('#app')
